import datetime
import locale
from django.db import models
from django.utils import timezone
from microerp.apps.base.models import Users
from microerp.apps.customer.models import Customer
from microerp.apps.product.models import Product


class SalesOrder(models.Model):
    SO_State = (
        (0, 'Created'),
        (1, 'Shipping'),
        (2, 'Completed'),
        (3, 'Cancel'),
    )
    user = models.ForeignKey(Users, on_delete=models.CASCADE)  # 所属用户
    so_num = models.CharField(max_length=10)  # 订单号  自动生成  SO-160301120132
    so_state = models.IntegerField(choices=SO_State, default=0)  # 订单状态
    so_cust = models.ForeignKey(Customer)  # 对应客户
    so_phone = models.CharField(max_length=50)
    so_address = models.TextField()
    so_note = models.TextField(blank=True)  # 订单备注
    so_trackingcompany = models.CharField(max_length=50)  # 物流公司
    so_trackingnum = models.CharField(max_length=40)  # 物流单号
    so_creattime = models.DateField(default=timezone.now)  # 订单创建时间

    # 自动设置销售订单编号
    def convert_No(self):
        # 返回销售订单编号
        count = SalesOrder.objects.filter(user=self.user).count()
        if count is not 0:
            lasted_so = SalesOrder.objects.filter(user=self.user).latest('id')
            num = int(lasted_so.so_num[3:]) + 1
            self.so_num = 'so-' + str(num)
        else:
            self.so_num = 'so-1'
        return self

    # 替代文本中的 \r 为 \r\n
    # 如果不转换 ，读取之后在页面上显示的效果就是一行
    def replace_Txt(self):
        self.so_comments = self.so_comments.replace("\n", "\r\n")
        return self

    # 获得该订单的客户名
    def get_cust(self):
        return self.so_cust.name

    # 得到该销售订单下的所有销售行
    def get_quantity(self):
        return SalesLine.objects.filter(sl_so=self).count()

    # 该销售订单的总价格
    def get_amount(self):
        total_dict = SalesLine.objects.filter(
            sl_so=self).aggregate(models.Sum('sl_price'))
        if total_dict['sl_price__sum']:
            # Set the locale for your system
            locale.setlocale(locale.LC_ALL, '')
            total = locale.format("%.2f", float(
                total_dict['sl_price__sum']), 1)
            return '￥' + total
        else:
            return '￥0'


'''
销售行( SalesOrder line)模型(销售订单的子对象)
'''


class SalesLine(models.Model):
    sl_so = models.ForeignKey(SalesOrder, on_delete=models.CASCADE)  # 所对应的销售订单
    sl_prod = models.ForeignKey(Product)  # 销售行中的产品
    sl_quantity = models.IntegerField()  # 交易产品数量
    sl_price = models.FloatField()  # 交易价格（单价

    def get_amount(self):
        return '￥' + locale.format("%.2f", float(self.sl_price * self.sl_quantity), 1)
